package cn.itcast.mobilebrowser.activity;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Patterns;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.PopupWindow;
import android.widget.Toast;

import java.util.Date;

import cn.itcast.mobilebrowser.R;
import cn.itcast.mobilebrowser.model.BookMark;
import cn.itcast.mobilebrowser.model.History;
import cn.itcast.mobilebrowser.model.WebTab;
import cn.itcast.mobilebrowser.viewmodel.BookMarkViewModel;
import cn.itcast.mobilebrowser.viewmodel.HistoryViewModel;
import cn.itcast.mobilebrowser.viewmodel.WebTabViewModel;


public class BrowserActivity extends AppCompatActivity implements View.OnClickListener, OnMenuItemClickListener {

    private static final String TAG = "BrowserActivity";

    // 把Button改成了ImageButton
    private EditText site_title;
    private ImageButton btn_backward;
    private ImageButton btn_forward;
    private ImageButton btn_multiWindow;
    private ImageButton btn_refresh;
    private ImageButton btn_toHome;
    private ImageButton btn_menu;
    private Button btn_sure;
    private ImageButton btn_x;
    // 添加书签时输入的title和url
    private EditText et_title;
    private EditText et_url;
    private WebView webView;
    private PopupWindow popupWindow;
    private long exitTime = 0;

    private BookMarkViewModel bookMarkViewModel;
    private HistoryViewModel historyViewModel;
    private WebTabViewModel webTabViewModel;

    InputMethodManager manager;//输入法管理器
//    WebSettings settings = webView.getSettings();

    // 用于启动书签页做返回，返回的url在WebView中打开
    private ActivityResultLauncher<Intent> launcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);
//        //webView设置
//        settings.setLoadWithOverviewMode(true); //自适应屏幕
//        settings.setUseWideViewPort(true);  //支持viewport
//        settings.setBuiltInZoomControls(true);
//        settings.setDisplayZoomControls(false);
//        settings.setSupportZoom(true);  //设定支持缩放
        webTabViewModel = new ViewModelProvider(this).get(WebTabViewModel.class);
        historyViewModel = new ViewModelProvider(this).get(HistoryViewModel.class);
        manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        bindViews();

        launcher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        // 返回码正确时保证intent不是空指针
                        if (RESULT_OK == result.getResultCode()) {
                            // 拿到返回的url
                            Intent data = result.getData();
                            String url = data.getExtras().getString("url");
                            Log.d("BrowserActivity", url);
                            webView.loadUrl(url);
                        }
                    }
                });

        webTabViewModel.getCurrentTab().observe(this, new Observer<WebTab>() {
            @Override
            public void onChanged(WebTab webTab) {
                Toast.makeText(BrowserActivity.this,
                        webTab.getTitle(), Toast.LENGTH_SHORT).show();
                // 得到新的webview，对其进行设置
                WebView newWebView = webTab.getWebView();

                // TODO：用这个新的webview替换当前布局中的webview
            }
        });

    }



    private void bindViews() {
        site_title = findViewById(R.id.site_title);
        btn_backward = findViewById(R.id.backward_Button);
        btn_forward = findViewById(R.id.forward_Button);
        btn_multiWindow = findViewById(R.id.multiWindow_Button);
        btn_refresh = findViewById(R.id.refresh_Button);
        btn_toHome = findViewById(R.id.home_Button);
        btn_menu = findViewById(R.id.menu_Button);
        webView = findViewById(R.id.webView);

        btn_backward.setOnClickListener(this);
        btn_forward.setOnClickListener(this);
        btn_multiWindow.setOnClickListener(this);
        btn_refresh.setOnClickListener(this);
        btn_toHome.setOnClickListener(this);
        btn_menu.setOnClickListener(this);

        site_title.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == event.KEYCODE_ENTER){
                    //TO DO
                    Toast.makeText(BrowserActivity.this,"你点击了回车",Toast.LENGTH_SHORT).show();
                    if (manager.isActive()){
                        manager.hideSoftInputFromWindow(site_title.getApplicationWindowToken(),0);
                    }
                    String url = site_title.getText().toString();
                    if(!(url.startsWith("http://")||url.startsWith("https://"))){
                        url = "http://"+url;
                    }
                    if (!Patterns.WEB_URL.matcher(url).matches() ){
                        url = "http://m.baidu.com/s?word=" + site_title.getText().toString();
                    }
                    webView.loadUrl(url);
                }
                return false;
            }
        });

        webView.loadUrl("http://www.baidu.com");
        webView.setDrawingCacheEnabled(true);

        webView.setWebChromeClient(new WebChromeClient() {
            //设置获取到的网站title
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                site_title.setText(title);
            }
        });


        webView.getSettings().setJavaScriptEnabled(true);//启用js
        webView.getSettings().setBlockNetworkImage(false);//解决图片不显示

        // 添加js交互接口类，并起别名 imagelistner代表MJavascriptInterface
        webView.addJavascriptInterface(new MJavascriptInterface(this), "imagelistner");
        //添加监听，通过调用js函数进行监听
        webView.setWebViewClient(new MyWebViewClient());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.backward_Button:
                webView.goBack();
                webView.goBack();
                break;
            case R.id.forward_Button:
                webView.goForward();
                break;
            case R.id.multiWindow_Button:
                // TODO：跳转多窗口
                getSupportFragmentManager().beginTransaction()
                        .setCustomAnimations(R.anim.popup_in, R.anim.popup_out)
                        .replace(R.id.container, WebTabFragment.newInstance())
                        .commitNow();
                break;
            case R.id.refresh_Button:
                webView.reload();   //刷新当前页面
                break;
            case R.id.home_Button:
                webView.loadUrl("http://www.baidu.com");    //回到首页
                break;
            case R.id.menu_Button:
                //创建弹出式菜单对象（最低版本11）
                PopupMenu popup = new PopupMenu(this, v);//第二个参数是绑定的那个view
                //获取菜单填充器
                MenuInflater inflater = popup.getMenuInflater();
                //填充菜单
                inflater.inflate(R.menu.pop_menu, popup.getMenu());
                //绑定菜单项的点击事件
                popup.setOnMenuItemClickListener(this);
                //显示
                popup.show();
                break;
        }
    }

    //弹出式菜单的单击事件处理
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        // 获取当前页的网址
        String now_url = webView.getUrl();
        switch (item.getItemId()) {
            // 添加书签事件
            case R.id.add:
                //显示弹窗，并返回对应的view
                View popView = showAddWindow();
                et_title = popView.findViewById(R.id.et_title);
                et_url = popView.findViewById(R.id.et_url);
                btn_sure = popView.findViewById(R.id.bt_sure);
                btn_x = popView.findViewById(R.id.btn_x);

                et_url.setText(now_url);
                //点击确定添加书签
                btn_sure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String get_title = et_title.getText().toString();
                        String get_url = et_url.getText().toString();
                        if(get_title.equals("")){
                            Toast.makeText(BrowserActivity.this, "请输入标题", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        BookMark bookMark = new BookMark(get_title, get_url);
                        // 初始化ViewModel
                        bookMarkViewModel = new ViewModelProvider(BrowserActivity.this).get(BookMarkViewModel.class);
                        bookMarkViewModel.insert(bookMark);
                        Toast.makeText(BrowserActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                        popupWindow.dismiss();
                    }
                });
                //点击“X”形图片的关闭pop框
                btn_x.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
                break;
            case R.id.book_marks:
                Intent intent1 = new Intent(this, BookMarksActivity.class);
                // 传输当前地址，供返回时使用
                intent1.putExtra("prior_url", now_url);
                intent1.putExtra("position", 0);
                launcher.launch(intent1);
                Toast.makeText(this, "书签", Toast.LENGTH_SHORT).show();
                break;
            case R.id.history:
                Intent intent2 = new Intent(this, BookMarksActivity.class);
                // 传输当前地址，供返回时使用
                intent2.putExtra("prior_url", now_url);
                intent2.putExtra("position", 1);
                launcher.launch(intent2);
                Toast.makeText(this, "历史记录", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        return false;
    }

    //添加书签的弹窗
    private View showAddWindow() {
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View vPopupWindow = inflater.inflate(R.layout.add_bookmarks_layout, null, false);//引入弹窗布局
        popupWindow = new PopupWindow(vPopupWindow, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        //设置背景透明
        addBackground();
        //设置进出动画
        popupWindow.setAnimationStyle(R.style.PopupWindowAnimation);
        //引入依附的布局
        View parentView = LayoutInflater.from(this).inflate(R.layout.activity_browser, null);
        //相对于父控件的位置（例如正中央Gravity.CENTER，下方Gravity.BOTTOM等），可以设置偏移或无偏移
        popupWindow.showAtLocation(parentView, Gravity.CENTER, 0, 0);
        // 需要设置一下此参数，点击外边可消失
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置点击窗口外边窗口消失    这两步用于点击手机的返回键的时候，不是直接关闭activity,而是关闭pop框
        popupWindow.setOutsideTouchable(true);

        return vPopupWindow;
    }

    //设置背景透明方法
    private void addBackground() {
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.7f;//调节透明度
        getWindow().setAttributes(lp);
        //dismiss时恢复原样
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
    }


    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
            webView.goBack();
        } else {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
        }
    }

    // js通信接口
    public class MJavascriptInterface {

        private Context context;

        public MJavascriptInterface(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void openImage(String url) {
            Intent intent = new Intent();
            intent.putExtra("url", url);
            intent.setClass(context, ShowWebImageActivity.class);
            context.startActivity(intent);
        }

    }

    // 监听
    private class MyWebViewClient extends WebViewClient {

        //webview里打开新连接
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(url.startsWith("http://")||url.startsWith("https://")){
                //加载的url是http/https协议地址
                webView.loadUrl(url);
                return false;
            }else {
                //加载的url是自定义协议地址
                try {
                    //调用手机浏览器打开url
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webView.getUrl()));
                    startActivity(intent);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return true;
            }
        }

        // 注入js函数监听
        private void addImageClickListner() {
            webView.getSettings().setJavaScriptEnabled(true);

            // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
            webView.loadUrl("javascript:(function(){" +
                    "setTimeout(() => {  " +
                    "var obj = document.images; " +
                    "try {" +
                    "       var testurl = document.getElementsByName('__SF__0')[0].src;" +  //获取百度上可以接收图片的网页
                    "       window.location.href = testurl;" +                              //跳转到该网页获取
                    "}catch(e){" +
                    "       ;" +
                    "}" +
                    "for(var i=0;i<obj.length;i++)  " +
                    "{" +
                    "obj[i].onclick=function()" +
                    "{  " +
                    "window.imagelistner.openImage(this.src);  " +
                    "};" +
                    "}" +
                    "}, 100);" +
                    "})()");
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            view.getSettings().setJavaScriptEnabled(true);
            super.onPageFinished(view, url);

            addImageClickListner();

            Log.d(TAG, "bindViews: " + view.getDrawingCache());
            // 添加历史记录
            if (!view.getTitle().isEmpty()) {
                History history = new History(view.getTitle(), url, new Date());
                historyViewModel.insert(history);
            }
            // TODO：该方法会被调用两次
            // TODO：取出的一直是同一张截图
            // 判断当前webview是否存在
            WebTab currentWebTab = webTabViewModel.getCurrentTab().getValue();
            if (currentWebTab != null) {
                // webview地址相同
                if (currentWebTab.getWebView() == view) {
                    currentWebTab.setTitle(view.getTitle());
                    currentWebTab.setImage(view.getDrawingCache());
                    webTabViewModel.setCurrentTab(currentWebTab);
                }
            } else {
                WebTab webTab = new WebTab();
                webTab.setTitle(view.getTitle());
                webTab.setImage(view.getDrawingCache());
                webTab.setWebView(view);

                webTabViewModel.addTab(webTab);
                webTabViewModel.setCurrentTab(webTab);
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);

            super.onPageStarted(view, url, favicon);
        }
    }

}
